package comm

import (
	"io"
	"log"
	"net"
	"time"
)

type ClientConf struct {
	Token    string
	CtrlConn net.Conn
	PortServ map[string]*net.Listener
}

func MakeTunnel(inStream net.Conn, outStream net.Conn) {
	log.Println("Make Tunnel:", inStream.RemoteAddr(), outStream.RemoteAddr())
	go io.Copy(inStream, outStream)
	io.Copy(outStream, inStream)
	log.Println("Exit Tunnel:", inStream.RemoteAddr(), outStream.RemoteAddr())
}

func SendCtrlMsg(strMsg string, c net.Conn) {
	_, err := c.Write(PackMsg([]byte(strMsg)))
	if err != nil {
		log.Println("SendCtrlMsg", err.Error())
	}
	log.Println("==============")
}

func WaitCtrlMsg(c net.Conn, t time.Duration) (sRet string, ok bool) {
	bBuff := make([]byte, 0)
	bTmp := make([]byte, 2048)
	if t > 0 {
		c.SetReadDeadline(time.Now().Add(t))
		log.Println("Set read timeout")
	}

	ok = true
	for {
		n, err := c.Read(bTmp)
		if err != nil {
			ok = false
			break
		}
		bBuff = append(bBuff, bTmp[:n]...)
		bMsg, ok := UnPackMsg(&bBuff)
		if ok {
			sRet = string(bMsg)
			break
		}
	}
	if t > 0 {
		c.SetReadDeadline(time.Unix(0, 0))
	}
	return
}

func SendCtrlMsgWait(strMsg string, c net.Conn, t time.Duration) (sRet string, ok bool) {
	SendCtrlMsg(strMsg, c)
	sRet, ok = WaitCtrlMsg(c, t)
	return
}
